var repairProjectStore = null;
var repairPremisesStore = null;
var repairBuildingStore = null;
var repairUnitStore = null;
var repairRoomStore = null;

Ext.define('component.areaRepair.areaRepairPanel', {
	extend : 'Ext.form.Panel',
	initComponent:function(){
		
		//项目
		repairProjectStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "projectName"],
	        proxy:{
	            type:'ajax',
	            url:contextPath+'/estate/project/findProjectList?resourcesCode=menu_0003_0001',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              }
	        } ,
	        autoLoad: false
		});
		repairProjectStore.load({
			callback:function(records, options, success){
				var count = repairProjectStore.getCount();
				if(count>0){
					var id = repairProjectStore.getAt(0).get("id");
					Ext.getCmp('repairProjectStore').setValue(id)
				}
				if(Ext.Array.contains(idata,"deal:list:all")){
					var data = {"projectName": "全部", "id": '-1'};
					var rs = Ext.create(data);
					repairProjectStore.insert(count+1, rs);
				}
			}
		});
		//组团
		repairPremisesStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "groupName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectPremises/findPremisesList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		
		repairPremisesStore.on("beforeload", function(){
			repairPremisesStore.removeAll();
			repairBuildingStore.removeAll();
			repairUnitStore.removeAll();
			repairRoomStore.removeAll();
			Ext.getCmp("repairPremisesStore").setValue("");
			Ext.getCmp("repairBuildingStore").setValue("")
			Ext.getCmp("repairUnitStore").setValue("")
			Ext.getCmp("repairRoomStore").setValue("")
			var projectId = Ext.getCmp("repairProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			repairPremisesStore.proxy.extraParams.projectId = projectId;
		});
		//楼栋
		repairBuildingStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "buildingName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectBuilding/findBuildingList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		repairBuildingStore.on("beforeload", function(){
			repairBuildingStore.removeAll();
			repairUnitStore.removeAll();
			repairRoomStore.removeAll();
			Ext.getCmp("repairBuildingStore").setValue("")
			Ext.getCmp("repairUnitStore").setValue("")
			Ext.getCmp("repairRoomStore").setValue("")
			var projectId = Ext.getCmp("repairProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("repairPremisesStore").getValue();
			repairBuildingStore.proxy.extraParams.projectId = projectId;
			repairBuildingStore.proxy.extraParams.premisesId = premisesId;
		});
		//单元
		repairUnitStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "unitName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectUnit/findUnitList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		repairUnitStore.on("beforeload", function(){
			repairUnitStore.removeAll();
			repairRoomStore.removeAll();
			Ext.getCmp("repairUnitStore").setValue("")
			Ext.getCmp("repairRoomStore").setValue("")
			var projectId = Ext.getCmp("repairProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("repairPremisesStore").getValue();
			var buildingId = Ext.getCmp("repairBuildingStore").getValue();
			repairUnitStore.proxy.extraParams.projectId = projectId;
			repairUnitStore.proxy.extraParams.premisesId = premisesId;
			repairUnitStore.proxy.extraParams.buildingId = buildingId;
		});
		//房间
		repairRoomStore = new Ext.data.Store({
	        singleton:true,
	        autoDestroy:true,
	        fields: ["id", "roomName"],
	        proxy:{
	   			type:'ajax',
	            url:contextPath+'/estate/projectRoom/findRoomList',
	            reader:{
                   type: 'json', 
                   root: 'root'  //数据
              	}
	        } ,
	        autoLoad: false
		});
		repairRoomStore.on("beforeload", function(){
			repairRoomStore.removeAll();
			Ext.getCmp("repairRoomStore").setValue("")
			var projectId = Ext.getCmp("repairProjectStore").getValue();
			if("-1" == projectId){
				projectId = "";
			}
			var premisesId = Ext.getCmp("repairPremisesStore").getValue();
			var buildingId = Ext.getCmp("repairBuildingStore").getValue();
			var unitId = Ext.getCmp("repairUnitStore").getValue();
			repairRoomStore.proxy.extraParams.projectId = projectId;
			repairRoomStore.proxy.extraParams.premisesId = premisesId;
			repairRoomStore.proxy.extraParams.buildingId = buildingId;
			repairRoomStore.proxy.extraParams.unitId = unitId;
		});
		
		var formsn = Ext.create("Ext.form.Panel", {
			minHeight:120,
		    title: "查询条件",
		    collapsible: true,  //可折叠
		    autoScroll: false,   //自动创建滚动条
		    defaultType: 'textfield',
		    fieldDefaults: {
		        margin: 2,
		        labelWidth: 80,
		        labelAlign: "right",
		        margin: "5 0 0 0"
		    },
		    items: [
		    	//权限资源隐藏字段
				{xtype:"textfield", name:"resourcesCode", value: resourcesCode, hidden: true},
				{xtype:"textfield", name:"resourcesName", value: "resName_area_list", hidden: true},
				{
				    xtype: "container",
				    layout: "hbox",
				    items: [
						{  
				            xtype:'combobox',
				            id:'repairProjectStore',
				            name: "projectId",
				            store: repairProjectStore,
				            valueField: "id",  
				            displayField: "projectName",
				            fieldLabel:'所属项目',
				            queryMode:'local',
				            typeAhead: false,
				            editable:false,
				            listeners:{
				            	'change':function(value){
				            		//加载组团数据
				            		if(value.lastValue && value.lastValue != "-1"){
				            			repairPremisesStore.load({
				            				callback: function(records, operation, success){
				            					//若无组团数据，加载楼栋
				            					var recordLen = records.length;
				            					if(recordLen == 0){
				            						repairBuildingStore.load();
				            					}
				            				}
				            			});
				            		}else{
				            			repairPremisesStore.removeAll();
				            			repairBuildingStore.removeAll();
				            			repairUnitStore.removeAll();
				            			repairRoomStore.removeAll();
				            			Ext.getCmp("repairPremisesStore").setValue("");
				            			Ext.getCmp("repairBuildingStore").setValue("")
				            			Ext.getCmp("repairUnitStore").setValue("")
				            			Ext.getCmp("repairRoomStore").setValue("")
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'repairPremisesStore',
				            name: "premisesId",
				            store: repairPremisesStore,
				            valueField: "id",  
				            displayField: "groupName",
				            queryMode:'local',
				            typeAhead: false,
				            editable:false,
				            listeners:{
				            	'change':function(value){
				            		//加载楼栋
				            		//若无楼栋数据，加载单元
				            		if(value.lastValue && value.lastValue != "-1"){
				            			repairBuildingStore.load({
				            				callback: function(records, operation, success){
				            					//若无组团数据，加载楼栋
				            					var recordLen = records.length;
				            					if(recordLen == 0){
				            						repairUnitStore.load();
				            					}
				            				}
				            			});
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'repairBuildingStore',
				            name: "buildingId",
				            store: repairBuildingStore,
				            valueField: "id",  
				            displayField: "buildingName",
				            queryMode:'local',
				            typeAhead: false,
				            editable:false,
				            listeners:{
				            	'change':function(value){
				            		//加载单元
				            		//若无单元数据，加载房间
				            		if(value.lastValue && value.lastValue != "-1"){
				            			repairUnitStore.load({
				            				callback: function(records, operation, success){
				            					//若无组团数据，加载楼栋
				            					var recordLen = records.length;
				            					if(recordLen == 0){
				            						repairRoomStore.load();
				            					}
				            				}
				            			});
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'repairUnitStore',
				            name: "unitId",
				            store: repairUnitStore,
				            valueField: "id",  
				            displayField: "unitName",
				            queryMode:'local',
				            typeAhead: false,
				            editable:false,
				            listeners:{
				            	'change':function(value){
				            		//加载房间
				            		if(value.lastValue && value.lastValue != "-1"){
				            			repairRoomStore.load();
				            		}
				            	}
				            }
				        },
						{  
				            xtype:'combobox',
				            id:'repairRoomStore',
				            name: "roomId",
				            store: repairRoomStore,
				            valueField: "id",  
				            displayField: "roomName",
				            queryMode:'local',
				            typeAhead: false,
				            editable:false
				        }
					]
				},{
		            xtype: "container",
		            layout: "hbox",
		            items: [
		                { xtype: "textfield", id: "customerNameStore", name:"customerName", fieldLabel: "客户名称"}
		            ]
		        },{
		            xtype: "container",
		            layout: "hbox",
		            items: [
			                { xtype: "datefield", id: "didTimeBeforeStore", name: "didTimeBefore", fieldLabel: "签约日期",format:'Y-m-d',typeAhead: false, editable:false},
			                {margin: "0 5 0 5",xtype: 'displayfield',value:'-'},
			                { xtype: "datefield", id: "didTimeAfterStore", name: "didTimeAfter", format:'Y-m-d',typeAhead: false, editable:false}
		            ]
		        }
//		        ,{ 
//	            	xtype: "checkboxgroup",
//	            	id:"ckStatuSn",
//	            	name:"m_auditStatus",
//	            	fieldLabel: "审核状态",
//	            	width:400,
//	            	items:[{
//    	            		boxLabel:'待提交',
//    	            		inputValue:'0'
//    	            	},{
//    	            		boxLabel:'已提交',
//    	            		inputValue:'1'
//    	            	},{
//    	            		boxLabel:'已通过',
//    	            		inputValue:'3'
//    	            	},{
//    	            		boxLabel:'已退回',
//    	            		inputValue:'2'
//    	            	}
//	                 ]
//                }
            ],
		    buttons: [
  	        	{ xtype: "button", text: "查询", 
	  	        	handler:function(){
	  	        		//获取通过checkboxgroup定义的checkbox值
	  	        		//审核状态
//	  	        		var ckStatusValue = Ext.getCmp('ckStatuSn').getChecked();
//	  	        		var ckStatus="";
//	  	        		Ext.Array.each(ckStatusValue, function(item){
//	  	        			ckStatus += item.inputValue+',' ;
//	  	        		});
//	  	        		
//	  	        		gridStoresn.getProxy().extraParams.m_auditStatus = ckStatus;
	  	        		gridStoresn.load();
	  	        		var pagingTool=Ext.getCmp("pagingTool");
	  	        		pagingTool.moveFirst();//跳至第一页
  	        		}  
  	        	},
	  	        { xtype: "button", text: "清空",
	  	        	handler:function(){
	  	        		formsn.getForm().reset();
	  	        	}
	  	        },
	  	        { hidden:dealReserveAreaExport, xtype: "button", text: "导出列表",
	  	        	handler:function(){
	  	        		var value = formsn.getForm().getValues();
                        console.log(JSON.stringify(value));
	  	        		location.href = jypath+'/deal/areaRepair/expExcel?value='+encodeURIComponent(JSON.stringify(value)) +'&ckStatus=';
	  	        		layer.alert("导出文件后只能编辑实测面积、​面积补差经办时间、面积补差应收时间​，修改其他字段会导致导入失败影响面积补差计算");
	  	        	}
	  	        },
	  	        { hidden:dealReserveAreaImport, xtype: "button", text: "导入面积补差",
	  	        	handler:function(){
	  	        		excelImport();
	  	        	}
	  	        }
  	    ]    
	});
	
	var gridStoresn = Ext.create('Ext.data.Store', {
        fields: ["id","didTime","customerName", "combinedName"
                 , "signCode","signPrice","signAmount"
                 ,"innerArea","buildingArea","measuredArea","totalRealAmount","userName"
                 ,"makeBalance" , "auditStatus","oppTime","mAuditStatus","calculateArea","balanceArea","measuredPrice"],
        pageSize: 10,  //页容量5条数据
        //是否在服务端排序 （true的话，在客户端就不能排序）
        remoteSort: false,
        proxy: {
            type: 'ajax',
            url: jypath+'/deal/areaRepair/list',
            actionMethods: { read: 'POST' },
            reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
                type: 'json', //返回数据类型为json格式
                root: 'rows',  //数据
                totalProperty: 'total' //数据总条数
            }
        },
        autoLoad: true  //即时加载数据
    });
	
	gridStoresn.on("beforeload",function(){
        Ext.apply(gridStoresn.proxy.extraParams,formsn.getForm().getValues());
        var projectId = Ext.getCmp("repairProjectStore").getValue();
        if(projectId == "-1"){
        	gridStoresn.proxy.extraParams.projectId = "";
        }
        var newResCode = resourcesCode + ",menu_0003_0001";
        gridStoresn.proxy.extraParams.resourcesCode = newResCode;
    });
	
	var gridsn = Ext.create('Ext.grid.Panel', {
		minHeight:600,
        store: gridStoresn,
        columnLines: true,
        columns: [{  
	        text : "查看",  
	        dataIndex: 'actioncolumn',
	        locked   : true,
	        renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
	            var rec = gridsn.getStore().getAt(rowIndex);
	            //查看
	            if(dealReserveAreaView==false){
	            	 return html = "<a href='"+jypath+"/marketing/reserveArea/addReserveArea?sigId="+rec.get('id')+"&menu="+menu+"' style='cursor:pointer'>查看</a>"; 	
	            }else{
	            	return null;
	            }
	           
	        }
        },{
            text: '签约日期',
            dataIndex: 'didTime',
            renderer:function(value){
            	return Ext.Date.format(new Date(value),'Y-m-d')
            }
        },{
            text     : '客户名称', 
            dataIndex: 'customerName'
        },{
            text     : '房号',
            dataIndex: 'combinedName',
            width:250
        },{
            text     : '合同编号',
            dataIndex: 'signCode'
        },{
            text     : '合同单价(元)',
            dataIndex: 'signPrice'
        },{
            text     : '合同总价(元)',
            dataIndex: 'signAmount'
        },{
            text     : '计价面积/<br>预测面积(平方米)',
            dataIndex: 'calculateArea',
        },{
            text     : '实测面积(平方米)',
            dataIndex: 'measuredArea',
            width:100
        },{
            text     : '面积差(平方米)',
            dataIndex: 'balanceArea',
            width:90
        },{
            text     : '面积补差价格(元)',
            dataIndex: 'makeBalance',
            width:100
        },{
            text     : '面积补差后总价(元)',
            dataIndex: 'measuredPrice',
            width:120
        }
        //,{
//            text     : '审核状态',
//            dataIndex: 'mAuditStatus',
//            renderer : function(val) {
//                if (val == 0) {
//                    return '待提交';
//                } else if (val == 1) {
//                    return '已提交';
//                }else if (val == 3) {
//                    return '已通过';
//                }else if (val == 2) {
//                    return '已退回';
//                }
//                return val;
//            }
//        },{
//            text     : '操作时间',
//            dataIndex: 'oppTime',
//            renderer:function(value){
//            	if(value)
//            	return Ext.Date.format(new Date(value),'Y-m-d')
//            }
//        },{
//            text     : '操作员',
//            dataIndex: 'userName'
//        },{  
//	        text : "操作",  
//	        dataIndex: 'actioncolumn',
//	        renderer: function(value,cellmeta,record,rowIndex,columnIndex,store) {
//	            var rec = gridsn.getStore().getAt(rowIndex);
//	            //查看
//	            if(dealReserveAreaView==false){
//	            	 return html = "<a href='"+jypath+"/marketing/reserveArea/addReserveArea?sigId="+rec.get('id')+"&menu="+menu+"' style='cursor:pointer'>查看</a>"; 	
//	            }else{
//	            	return null;
//	            }
//	           
//	        }
//        }
        ],
        title: '面积补差列表',
        dockedItems: [{  
            xtype: 'pagingtoolbar',  
            store: gridStoresn,   // GridPanel中使用的数据  
            dock: 'bottom',  
            displayInfo: true,  
            emptyMsg:"没有数据",  
            displayMsg:"显示从{0}条数据到{1}条数据，共{2}条数据",
            id:'pagingTool'
        }
        ]
    });
	
		
		var defaultConfigg = {
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true  //可以折叠
		        },
				items:[formsn,gridsn]
		};
		Ext.apply(this,defaultConfigg);
		this.callParent(arguments);
		
	}
});
function excelImport(){
	layer.open({
		type:2,
	    title: "导入面积补差",
	    closeBtn: 2,
	    shadeClose: true,
	    area: ['480px', '320px'],
	    fix: false, //不固定
	    content: jypath +'/deal/areaRepair/toExcelImport'
	});
}
